import dayjs from 'dayjs'
import RequireContext = __WebpackModuleApi.RequireContext

/**
 * @description 处理首字母大写 abc => Abc
 * @param str
 */
export const changeStr = (str: string) => {
    return str.charAt(0).toUpperCase() + str.slice(1)
}

/**
 * @description 批量导入文件
 * @param {Object} context 上下文对象
 * @param {RegExp} reg 匹配规则
 * @returns {Object} 对象
 */
export const importAllModule = (context: RequireContext, reg = /\.vue$/) => {
    return context.keys().reduce((compObj: any, fileName) => {
        const compName = changeStr(fileName.replace(/^\.\//, '').replace(/\.\w+$/, ''))
        compObj[compName] = context(fileName).default || context(fileName)
        return compObj
    }, {})
}

/**
 * @description 随机生成颜色
 * @param {string} type
 * @return {string}
 */
export const randomColor = (type: 'rgb' | 'hex' | 'hsl'): string => {
    switch (type) {
        case 'rgb':
            return window.crypto.getRandomValues(new Uint8Array(3)).toString()
        case 'hex':
            return (
                '#' +
                Math.floor(Math.random() * 0xffffff)
                    .toString(16)
                    .padStart(6, `${Math.random() * 10}`)
            )
        case 'hsl':
            // 在25-95%范围内具有饱和度，在85-95%范围内具有亮度
            return [360 * Math.random(), 100 * Math.random() + '%', 100 * Math.random() + '%'].toString()
    }
}

/**
 * 复制文本
 * @param text
 */
export const copyText = (text: string) => {
    return new Promise((resolve, reject) => {
        const copyInput = document.createElement('input') //创建一个input框获取需要复制的文本内容
        copyInput.value = text
        document.body.appendChild(copyInput)
        copyInput.select()
        document.execCommand('copy')
        copyInput.remove()
        resolve(true)
    })
}

/**
 * @description 判断字符串是否是base64
 * @param {string} str
 */
export const isBase64 = (str: string): boolean => {
    if (str === '' || str.trim() === '') {
        return false
    }
    try {
        return btoa(atob(str)) == str
    } catch (err) {
        return false
    }
}
/**
 * 对象转JSON
 * @param obj 
 */
export const toJSON = (obj) => {
    return JSON.stringify(obj, (key, value) => {
        switch (true) {
            case typeof value === 'undefined':
                return 'undefined'
            case typeof value === 'symbol':
                return value.toString()
            case typeof value === 'function':
                return value.toString()
            default:
                break
        }
        return value
    })
}

/**
 * 动态引入文件
 * @param name 文件名
 */
export const getSrc = (name) => {
    if (!name) return;
    const path = `../assets/images/${name}`
    const modules = import.meta.globEager('../assets/images/*')
    return modules[path].default
}

/***
 * @description 是否是生产环境
 */
export const isDev = import.meta.env.DEV

/***
 * @description 格式化日期
 * @param time
 */
export const formatDate = (time) => dayjs(time).format('YYYY-MM-DD HH:mm:ss')

/**
 * @description 过滤枚举
 * @param list 
 * @param key 
 */
export const filterEnum = (list, key) => {
    const data = list.filter(v => v?.code == key.toString())
    return data.length ? data[0].value : '枚举不匹配'
}

/**
 * 同步赋值对象字段
 * @param obj1 被赋值对象
 * @param obj2 赋值对象
 */
export const syncObj = (obj1, obj2) => {
    return Object.keys(obj1).forEach((key) => {
        if (obj2[key]) obj1[key] = obj2[key]
    })
}

/**
 * @description 将一维数组转成树形结构数据
 * @param items
 * @param id
 * @param link
 */
export const generateTree = (items, id = 0, link = 'parent') => {
    return items
        .filter((item) => item[link] == id)
        .map((item) => ({
            ...item,
            slots: { title: 'name' },
            children: generateTree(items, item.departmentid)
        }))
}

/***
 * @description 原生加密明文
 * @param {string} plaintext
 */
export const encryption = (plaintext: string) =>
    isBase64(plaintext) ? plaintext : window.btoa(window.encodeURIComponent(plaintext))

/**
 * @description 原生解密
 * @param {string} ciphertext
 */
export const decryption = (ciphertext: string) =>
    isBase64(ciphertext) ? window.decodeURIComponent(window.atob(ciphertext)) : ciphertext

/**
 * 获取密码强度
 * @param password 
 */
export const getPasswordStrength = (password) => {
    var strength = 0;
    [/.{6,}/, /[0-9]+/, /[a-z]+/, /[A-Z]+/, /[^0-9a-zA-Z]+/].forEach((v, i) => {
        if (v.test(password)) strength++;
    });
    return strength;
};

/**
 * 数组对象去重
 * @param array 
 */
export const objReduce = (array, key) => {
    let obj = {};
    let nodes = array.reduce((cur, next) => {
        obj[next[key]] ? "" : obj[next[key]] = true && cur.push(next);
        return cur;
    }, []) //设置cur默认类型为数组，并且初始值为空的数组
    return nodes
}